package com.jsb.laundry.jobs;

import com.alibaba.fastjson.JSONObject;
import com.jsb.laundry.common.utils.JSBUtil;
import com.jsb.laundry.common.utils.http.HttpUtil;
import com.jsb.laundry.config.properties.WechatMiniPayProperties;
import com.jsb.laundry.utils.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
@EnableScheduling
public class WechatAccessToken {

    private static final Logger LOGGER = LoggerFactory.getLogger(WechatAccessToken.class);

    private static RedisUtil redisUtil;
    private static WechatMiniPayProperties wechatMiniPayProperties;

    public WechatAccessToken(RedisUtil redisUtil, WechatMiniPayProperties wechatMiniPayProperties) {
        WechatAccessToken.redisUtil = redisUtil;
        WechatAccessToken.wechatMiniPayProperties = wechatMiniPayProperties;
    }

//    private final long fix = 1000 * 60 * 60;
//    @Async("myAsync")
//    @Scheduled(fixedRate = fix) //每5分钟执行一次
//    public void testScheduleTask() {
//        getWxAccessToken("wx66259c2db83de8c2","a751a2d916092083cbd85d4f58ffc0b5");//骑手端
//    }

    /**
     * 获取微信token
     * @param appId
     * @param secret
     * @return https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getStableAccessToken.html
     */
    public static String getWxAccessToken(String appId,String secret){
        //去redis获取新的 如果不存在就重新生成
//        String getWxAccessToken = redisUtil.getCacheObject(appId);
        String access_token = null;
        JSONObject object =null;
//        if (JSBUtil.isEmptyString(getWxAccessToken)){
            try {
                String url = "https://api.weixin.qq.com/cgi-bin/stable_token";
                JSONObject data =new JSONObject();
                data.put("grant_type","client_credential");
                data.put("appid",appId);
                data.put("secret",secret);
//            data.put("force_refresh",true);
                String dataList = HttpUtil.sendPost(url, null, JSONObject.toJSONString(data));
                object = JSONObject.parseObject(dataList);
                access_token = object.getString("access_token");
            }catch (Exception e){
                LOGGER.error(JSONObject.toJSONString(object));
            }
//        }
        return access_token;
    }

}
